import logging
import math
from typing import Optional, List

from fastapi import APIRouter, Depends, Query, Path
from pydantic import Field, BaseModel
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

waster_category_router = APIRouter(prefix="/wasteCategory", tags=["危废数据字典查询接口"],
                                   dependencies=[Depends(oauth2_scheme)])


class HazardousWasteCategorySearch(PaginationBase):
    # 筛选条件
    site_no: Optional[str] = Field("", description="站点编号")
    categoryName: Optional[str] = Field("", description="危废类别名称(支持前缀匹配)")
    categoryCode: Optional[str] = Field("", description="危废类别代码(支持前缀匹配)")


@waster_category_router.get("/list", summary="危废数据字典查询接口")
def list_waste_category(search: HazardousWasteCategorySearch = Query(), db: Session = Depends(get_db)):
    param = {}
    sql = "select count(1) from w_base_waste_category where 1=1"
    if search.site_no != "":
        sql = sql + " and fsite_no = :site_no "
        param["site_no"] = search.site_no
    if search.categoryName != "":
        sql = sql + " and category_name like concat('%', :categoryName ,'%')"
        param["categoryName"] = search.categoryName
    if search.categoryCode != "":
        sql = sql + " and category_code like concat('%', :categoryCode ,'%')"
        param["categoryCode"] = search.categoryCode
    count = db.execute(text(sql), param).scalar()

    param = {}
    sql = "select waste_category_id,category_name,category_code,status,create_at,create_by,update_at,update_by"
    sql = sql + " from w_base_waste_category where 1=1"
    if search.site_no != "":
        sql = sql + " and fsite_no = :site_no "
        param["site_no"] = search.site_no
    if search.categoryName != "":
        sql = sql + " and category_name like concat('%', :categoryName ,'%')"
        param["categoryName"] = search.categoryName
    if search.categoryCode != "":
        sql = sql + " and category_code like concat('%', :categoryCode ,'%')"
        param["categoryCode"] = search.categoryCode
    sql = sql + " order by  waste_category_id "
    sql = sql + " limit :limit offset :offset "
    param["offset"] = search.offset
    param["limit"] = search.limit
    data = db.execute(text(sql), param).fetchall()

    data_list = []
    for key in range(len(data)):
        d1 = {}
        d1['wasteCategoryId'] = data[key][0]
        d1['categoryName'] = data[key][1]
        d1['categoryCode'] = data[key][2]
        d1['status'] = data[key][3]
        d1['createAt'] = data[key][4]
        d1['createBy'] = data[key][5]
        d1['updateAt'] = data[key][6]
        d1['updateBy'] = data[key][7]
        data_list.append(d1)

    info_dict = {"list": data_list,
                 "limit": search.limit,
                 "page": search.pageIndex,
                 "pages": (count + search.limit - 1) // search.limit,
                 "total": count}
    return BaseResponse.success(data=info_dict)
